<template>
	<view class="goshop-head-container">
		<u-sticky bgColor="#fff">
			<view class="goshop-head-bg"></view>
			<view class="goshop-head-wrap u-p-x-20">
					<view class="goshop-head-tabs">
										<view @click="tabClick(index)" v-for="(item,index) in list" :id="'item-id-'+index" :key="index"
											:class="['goshop-head-tabs-item',current==index?'active':'']">{{item.name}}</view>
					</view>
					<u-search placeholder="请输入搜索关键字" v-model="keyword" :showAction="false"></u-search>
			</view>
		</u-sticky>
	</view>
</template>

<script>
	export default {
		name:"goshop-home-head",
		data() {
			return {
				scrollLeft: 0,
				parentLeft: 0,
				current: 1,
				keyword: '',
				tabQueryInfo: [],
				list: [{
                    name: '关注',
                }, {
                    name: '推荐',
                }, {
                    name: '同城'
                }]
			};
		},
		onReady() {
			this.init();
		},
		methods: {
            click(item) {
                console.log('item', item);
            },
			async init() {
				const res = await this.$u.getRect('.goshop-head-tabs');
				this.parentLeft = res.left;
				// tabs组件的宽度
				this.componentWidth = res.width;
				let query = uni.createSelectorQuery().in(this);
				for (let i in this.list) {
					query.select(`#item-id-${i}`).fields({
						size: true,
						rect: true
					})
				}
				query.exec(
					function(res) {
						this.tabQueryInfo = res;
						this.scrollByIndex();
					}.bind(this)
				);
			},
			scrollByIndex() {
				let tabInfo = this.tabQueryInfo[this.current];
				let tabWidth = tabInfo.width;
				console.log(tabInfo)
				console.log(tabWidth)
				console.log(this.componentWidth)
				let offsetLeft = tabInfo.left - this.parentLeft;
				let scrollLeft = offsetLeft - (this.componentWidth - tabWidth) / 2;
				console.log(scrollLeft)
				this.scrollLeft = scrollLeft < 0 ? 0 : scrollLeft;
			},
			tabClick(e) {
				this.current = e;
				this.scrollByIndex();
				this.$nextTick(() => {

				})
			}
		}
	}
</script>

<style lang="scss">
.goshop-head-container{
	.goshop-head-bg{
		// position: absolute;
		// top: 0px;
		// left: 0;
		// right: 0;
		// height: 300rpx;
		// //background-color: #ff0000;
		position: fixed;
		width: 100%;
		height: 300rpx;
		top: 0;
		left: 0;
		background-color: #ff0000;
		z-index: -1;
	}
}
.goshop-head-wrap{
	height: 190rpx;
	//width: 100%;
	//background-color: $goshop-color-primary;
	.goshop-head-tabs{
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		.goshop-head-tabs-item {
				display: inline-block;
				width: 25%;
				text-align: center;
				line-height: 80rpx;
				color: $goshop-color-auxiliary-one;
				&.active {
					color: $goshop-color-auxiliary-four;
					font-weight: bold;
				}
			}
	}
}
</style>